package top.codedance.iotp.client.manage.net;

import top.codedance.iotp.client.manage.ManageApplication;
import top.codedance.iotp.client.manage.net.listenner.SerialPortListener;
import top.codedance.iotp.common.util.SystemUtil;
import com.fazecast.jSerialComm.SerialPort;
import org.apache.log4j.Logger;

import java.io.*;

public class ComServer {
    private Logger logger = ManageApplication.getLogger(ComServer.class);
    private SerialPort mSerialPort = null;
    private String comName;
    private int baudRate;

    public ComServer(int baudRate) {
        this.baudRate = baudRate;
        comName = initConfig();
        connect();
        long time = System.currentTimeMillis();
        while (true) {
            if (mSerialPort == null || !mSerialPort.isOpen()) {
                connect();
                logger.info("Com[" + comName + "] sever is reconnect!");
            }else{
                if(System.currentTimeMillis() - time > 1000 * 3600 * 2){
                    close();
                    connect();
                    time = System.currentTimeMillis();
                }
            }
            try {
                Thread.sleep(3000);
            } catch (Exception ex) { }
        }
    }

    private void connect() {
        mSerialPort = SerialPort.getCommPort(comName);
        mSerialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        mSerialPort.setComPortParameters(baudRate, 8, 1, 0);
        mSerialPort.addDataListener(new SerialPortListener(this));
        if (!mSerialPort.openPort(0, 1024 * 1024 * 2, 1024 * 1024 * 2)) {
            mSerialPort = null;
        }
        logger.info("Com server is running!");
    }

    public boolean isOpen(){
        return mSerialPort.isOpen();
    }

    public String initConfig() {
        String comName = "COM1";
        String runtimeDirPath = SystemUtil.getRuntimeDirPath(ManageApplication.class);
        String iniFilePath = runtimeDirPath + "com.cnf";
        File f = new File(iniFilePath);
        if (f.exists()) {
            try {
                BufferedReader br = new BufferedReader(new FileReader(f));
                comName = br.readLine();
                br.close();
            } catch (IOException e) {
                logger.debug("Cnf file configure fail.");
            }
        } else {
            try {
                f.createNewFile();
                BufferedWriter bw = new BufferedWriter(new FileWriter(f));
                bw.write(comName);
                bw.close();
            } catch (Exception e) {
                logger.debug("Create cnf file fail.");
            }
        }
        return comName;
    }

    public void close(){
        if(mSerialPort != null && mSerialPort.isOpen()) {
            mSerialPort.closePort();
        }
    }
}
